package com.qiwo.common.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
 * Copyright
 *
 * @Author:chenwenchao
 * @Date:2018/6/14 Description:
 */
public class HttpResponseHelper {

    /**
     * 直接返回json退出
     * @param json
     * @param response
     */
    public static  void responeWrite(String json,  HttpServletResponse response){
//将字符转换成字节数组，指定以UTF-8编码进行转换
        byte[] dataByteArr = new byte[0];
        try {
            dataByteArr = json.getBytes("UTF-8");
            //获取OutputStream输出流
            OutputStream outputStream = response.getOutputStream();
            //通过设置响应头控制浏览器以UTF-8的编码显示数据，如果不加这句话，那么浏览器显示的将是乱码
            response.setHeader("content-type", "text/json;charset=UTF-8");
            //使用OutputStream流向客户端输出字节数组
            outputStream.write(dataByteArr);
            outputStream.flush();
            outputStream.close();
            return;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
